package com.shsnc.agent.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ReflectUtil;
import com.shsnc.agent.annotation.FiledInfo;

/**
 *
 * @author zll
 * @date 2021/8/5
 */
public class FiledInfoUtil<T> {

	/**
	 * 注解列表
	 */
	private List<Field> fields;

	/**
	 * 实体对象
	 */
	public Class<T> clazz;

	public FiledInfoUtil(Class<T> clazz)
	{
		this.clazz = clazz;
		putToFields();
	}

	public Map<String,String> deal(Object o){
		Map<String,String> map=new HashMap<>();
		for (int j = 0; j < fields.size(); j++) {
			// 获得field.
			Field field = fields.get(j);
			FiledInfo attr = field.getAnnotation(FiledInfo.class);
			if(attr==null){
				continue;
			}
			String key=attr.name();
			Object value= ReflectUtil.getFieldValue(o,field);
			if(value==null){
				value="";
			}
			map.put(key, value.toString());
		}
		return map;
	}



	/**
	 * 放到字段集合中
	 */
	private void putToFields()
	{

		List<Field> tempFields = new ArrayList<>();
		Class<?> tempClass = clazz;
		tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
		while (tempClass != null)
		{
			tempClass = tempClass.getSuperclass();
			if (tempClass != null) {
				tempFields.addAll(Arrays.asList(tempClass.getDeclaredFields()));
			}
		}
		this.fields = new ArrayList<Field>();
		for (Field field : tempFields)
		{
			FiledInfo attr = field.getAnnotation(FiledInfo.class);
			if (attr != null )
			{
				this.fields.add(field);
			}
		}
	}
}
